/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.admin.controller;

import com.admin.model.EventInfoFacadeLocal;
import com.common.json.JsonModel;
import com.entities.EventInfo;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import org.json.simple.JSONObject;

/**
 *
 * @author Tuan Long
 */
@Stateless
public class CreateEventEJB implements CreateEventEJBRemote {
    @EJB
    private EventInfoFacadeLocal eventInfoFacade;

    
    /**
     * @CreateEventEJB.createEvent : insert new event record to EventLibrary and EventInfo at the same time
     * table
     * @param jsonstr
     * @return boolean
     *
     */
    @Override
    public boolean createEvent(String jsonstr) {        
        try {
            JSONObject json = JsonModel.JsonDecoder(jsonstr);
            String idstr = json.get("eventId").toString();
            int id = Integer.parseInt(idstr);
            String name = json.get("name").toString();
            String des = json.get("description").toString();
            String type = json.get("eventType").toString();
            String start = json.get("start").toString();
            String end = json.get("end").toString();
            Date timeS = convertStringToDatetime(start);
            Date timeE = convertStringToDatetime(end);
            String avatar = json.get("avatar").toString();
            String shortdes = json.get("shortdes").toString();
            String address =json.get("address").toString();
            boolean b = eventInfoFacade.createNewEvent(name,des,type,timeS,timeE,avatar,shortdes,address);
            return b;
        } catch (NumberFormatException e) {
            System.out.println(e.getMessage());
            return false;
        }
    }

    private Date convertStringToDatetime(String str) {
        try {
            SimpleDateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            Date date = df.parse(str);
            return date;
        } catch (ParseException ex) {
            Logger.getLogger(CreateEventEJB.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null;
    }

    @Override
    public String getEventContentById2(int eventId) {        
        EventInfo ei = eventInfoFacade.getEventInfoByEventId(eventId);        
        String json ="";
        if(ei != null){
            json = JsonModel.getEventContentById2Sender(ei);
        }        
        return json;
    }

}
